package com.feng.security.config;

import com.alibaba.fastjson.JSON;
import com.feng.common.api.ResponseResult;
import com.feng.common.api.ResultCode;
import com.feng.common.config.FileConfig;
import com.feng.common.utils.WebUtil;
import com.feng.security.filter.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author Feng
 * @since 2022/4/17 18:05
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Autowired
    JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Bean
    AccessDeniedHandler jwtAccessDeniedHandler() {
        //当用户在没有授权的情况下访问受保护的REST资源时，将调用此方法发送403 Forbidden响应
        return (request, response, e) -> {
            ResponseResult result = new ResponseResult(ResultCode.FORBIDDEN);
            String json = JSON.toJSONString(result);
            WebUtil.renderString(response, json);
        };
    }

    @Bean
    AuthenticationEntryPoint authenticationEntryPoint() {
        // 当用户尝试访问安全的REST资源而不提供任何凭据时，将调用此方法发送401 响应
        return (request, response, e) -> {
            ResponseResult result = new ResponseResult(ResultCode.UNAUTHORIZED);
            String json = JSON.toJSONString(result);
            WebUtil.renderString(response, json);
        };
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 关闭csrf
                .csrf().disable()
                // 关闭基于Session的登录信息管理
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 允许登录和验证码接口匿名访问（anonymous登录后就不能访问了，与permitAll不同）
                .antMatchers("/auth/login", "/auth/code").anonymous()
                // 文件
                .antMatchers(FileConfig.ACCESS_PATH  + "**").permitAll()
                // 其他接口都需认证
                .anyRequest().authenticated()
                .and()
                .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
                .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint()) // 401
                .accessDeniedHandler(jwtAccessDeniedHandler()) // 403
                // 允许跨域
                .and()
                .cors();
    }
}
